//
//  CitiesSelectViewController.m
//  NOAHWM
//
//  Created by Frank on 6/17/13.
//  Copyright (c) 2013 Ryan. All rights reserved.
//

#import "CitiesSelectViewController.h"
#import "JSON.h"
#import "SectionView.h"

@interface CitiesSelectViewController ()

@end

@implementation CitiesSelectViewController

@synthesize gpsLocation;
@synthesize selectedLocation;

@synthesize citiesTableView;

@synthesize nameIndexDict;
@synthesize selectedDict;

@synthesize searchBar;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.nameIndexDict = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setLeftNaviItemWithTitle:nil imageName:@"Icon_Back"];
    [self setRightNaviItemWithTitle:nil imageName:nil];
    [self setNaviTitle:@"分公司城市列表"];
    self.selectedDict = [NSMutableDictionary dictionary];
    [self resetSearch];
    [self.citiesTableView reloadData];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if (self.isViewLoaded&&!self.view.window) {
        self.gpsLocation = nil;
        self.citiesTableView = nil;
        self.selectedLocation = nil;
        self.nameIndexDict = nil;
        self.selectedDict = nil;
        self.searchBar = nil;
    }
}

- (void)viewDidUnload{
    self.gpsLocation = nil;
    self.citiesTableView = nil;
    self.selectedLocation = nil;
    self.nameIndexDict = nil;
    self.selectedDict = nil;
    self.searchBar = nil;
}

-(void)dealloc {
    [gpsLocation release];
    [citiesTableView release];
    [selectedLocation release];
    [nameIndexDict release];
    [selectedDict release];
    [searchBar release];
    [super dealloc];
}

#pragma mark - BaseViewController methods
- (void)leftItemTapped
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - table view datasource delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.f;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (0 == section) {
        return 1;
    }
    NSInteger tmp = section -1;
    NSArray *indexArray = [[self.selectedDict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    NSMutableArray *rearray = [self.selectedDict objectForKey:[indexArray objectAtIndex:tmp]];
    return rearray.count;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return  self.selectedDict.count + 1 ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentify = @"cellIdentify";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if(nil == cell)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
//        CGRect backImageRect = CGRectMake(0.0, 0.0, 320.0, 33.0);
//        UIImageView *backImage = [[UIImageView alloc] initWithFrame:backImageRect];
//        //backImage.image = [UIImage imageNamed:@"Shape_list@2x.png"];
//        [cell.contentView addSubview:backImage];
//        [backImage release];
        
        CGRect lineImageRect = CGRectMake(0.0, 0.0, 320.0, 1.0);
        UIImageView *lineImage = [[UIImageView alloc] initWithFrame:lineImageRect];
        lineImage.image = [UIImage imageNamed:@"Login_line@2x.png"];
        [cell.contentView addSubview:lineImage];
        [lineImage release];
        
        CGRect titleValueRect = CGRectMake(10.0, 5.0, 100.0, 32.0);
        UILabel *titleValue = [[UILabel alloc] initWithFrame:titleValueRect];
        titleValue.tag = 101;
        titleValue.backgroundColor = [UIColor clearColor];
        titleValue.textAlignment = UITextAlignmentLeft;
        titleValue.font = [UIFont systemFontOfSize:15];
        titleValue.adjustsFontSizeToFitWidth = YES;
        titleValue.minimumFontSize = 10;
//        titleValue.textColor = [UIColor colorWithRed:202/255.0 green:41/255.0 blue:11/255.0 alpha:1.0];
        titleValue.textColor = [UIColor blackColor];
        [cell.contentView addSubview:titleValue];
        [titleValue release];
        
        CGRect descriptionValueRect = CGRectMake(120.0, 1.0, 200.0, 32.0);
        UILabel *descriptionValue = [[UILabel alloc] initWithFrame:descriptionValueRect];
        descriptionValue.tag = 102;
        descriptionValue.backgroundColor = [UIColor clearColor];
        descriptionValue.textAlignment = UITextAlignmentLeft;
        descriptionValue.font = [UIFont systemFontOfSize:15];
        descriptionValue.adjustsFontSizeToFitWidth = YES;
        descriptionValue.minimumFontSize = 10;
//        descriptionValue.textColor = [UIColor colorWithRed:202/255.0 green:41/255.0 blue:11/255.0 alpha:1.0];
        descriptionValue.textColor = [UIColor grayColor];
        [cell.contentView addSubview:descriptionValue];
        [descriptionValue release];
        
        cell.backgroundColor = [UIColor clearColor];
    }
    
    UILabel *titleValue = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *descriptionValue = (UILabel *)[cell.contentView viewWithTag:102];
    
    if (indexPath.section == 0)
    {
        titleValue.text = self.gpsLocation;
        descriptionValue.text = @"";
        if ([self.selectedLocation isEqualToString: [NSString stringWithFormat:@"%@", titleValue.text]])
        {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else{
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    else
    {
        NSArray *indexArray = [[self.selectedDict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
       
        titleValue.text = [[self.selectedDict objectForKey:[indexArray objectAtIndex:indexPath.section-1]] objectAtIndex:indexPath.row];
        descriptionValue.text = @"";
        if ([self.selectedLocation isEqualToString: [NSString stringWithFormat:@"%@", titleValue.text]])
        {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else{
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20.f;
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *sectionName;
    if (section == 0) {
        sectionName = @"GPS定位最近的分公司城市";
    }
    else{
        NSArray *indexArray = [[self.selectedDict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
        sectionName = [indexArray objectAtIndex:section-1];
    }
    return sectionName;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"SectionView" owner:self options:nil];
    SectionView *sv = (SectionView *)[nibs lastObject];
    
    NSArray *indexArray = [[self.selectedDict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    if (section == 0) {
        sv.titleLabel.text = @"GPS定位最近的分公司城市";
    }
    else{
        sv.titleLabel.text = [indexArray objectAtIndex:section-1];
    }
    return sv;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSArray *indexArray = [[self.selectedDict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    return indexArray;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    
    NSInteger count = 0;
    NSArray *nameArray = [[self.selectedDict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    for(NSString *character in nameArray)
        
    {
        if([character isEqualToString:title])
        {
            return count+1;
        }
        
        count ++;
        
    }
    return count+1;
}

#pragma mark - table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row = indexPath.row;
    int section = indexPath.section;
    [tableView  deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section != 0) {
        NSArray *indexArray = [[self.selectedDict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
        NSString *text = [[self.selectedDict objectForKey:[indexArray objectAtIndex:(section-1)]] objectAtIndex:row];
    
        [[NSNotificationCenter defaultCenter] postNotificationName:kSelectedBlanchCityNotification object:text];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else{
        [[NSNotificationCenter defaultCenter] postNotificationName:kSelectedBlanchCityNotification object:self.gpsLocation];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - searchbar delegate

-(void)resetSearch
{
    for (NSString *index in [self.nameIndexDict allKeys]) {
        NSMutableArray *array = [self.nameIndexDict objectForKey:index];
        NSMutableArray *newArray = [NSMutableArray array];
        for (NSString *name in array) {
            NSString *newname = [NSString stringWithString:name];
            [newArray addObject:newname];
        }
        [self.selectedDict setObject:newArray forKey:index];
    }
}

-(void)handleSearchForTerm:(NSString *)searchTerm
{
    [self resetSearch];
    
    NSArray *indexArray = [[self.selectedDict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    for (NSString *name in indexArray) {
        NSMutableArray *citysInGroup = [NSMutableArray arrayWithArray: [self.selectedDict objectForKey:name]];
        for (NSString *element in citysInGroup) {
            if ([element rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound) {
                [[self.selectedDict objectForKey:name] removeObject:element];
            }
        }
        NSMutableArray *tmp = [self.selectedDict objectForKey:name];
        if (tmp.count == 0) {
            [self.selectedDict removeObjectForKey:name];
        }
    }

    [self.citiesTableView reloadData];
}


-(void)searchBarSearchButtonClicked:(UISearchBar *)MysearchBar
{
    NSString *searchTerm=[MysearchBar text];
    [self handleSearchForTerm:searchTerm];
    [self.searchBar resignFirstResponder];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if([searchText length]==0)
    {
        [self resetSearch];
        [self.citiesTableView reloadData];
        [self.searchBar resignFirstResponder];
        return;
    }
    [self handleSearchForTerm:searchText];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

@end
